package com.assets.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.assets.bean.ReceivesDetailNew;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.ReceivesDetail;
import com.assets.room.entity.Returns;
import com.assets.room.entity.User;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.demo.WaveSwipeRefreshLayout;
import com.assets.Adapter.Public_list_item_Adapter;
import com.assets.Back.back;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.bean.Repairs_bean;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/12/25.
 */

public class Fragment6 extends Fragment {

    private static final String TAG = "这个是归还的页面";
    private ImageView imageView, screen, add;
    private String url = "http://" + Url.IP + "/api/returnsQuery";
    private ListView lv_list;
    private String id;
    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    private SlideSideMenuExampleActivity content;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_second6, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        content = (SlideSideMenuExampleActivity) getActivity();
        SharedPreferences mm = getActivity().getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id", "");
        init();
    }

    private void init() {

        TextView title = content.findViewById(R.id.title_text);
        title.setText("归还");
        screen = (ImageView) content.findViewById(R.id.screen);
        add = (ImageView) content.findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(content, back.class);
                startActivity(intent);
            }
        });
        lv_list = (ListView) getActivity().findViewById(R.id.fragment2_list);
        imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
                mSlideSideMenu.toggle();
            }
        });
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {//模拟3秒的加载过程
                    @Override
                    public void run() {
                        load();
                        //接下来可以刷新ListView
                    }
                }, 1200);
            }
        });
        screen.setOnClickListener(v -> new AlertView("筛选", null, "取消", new String[]{"全部"}, new String[]{"申请中", "通过", "驳回"}, content, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    //适配器，刚刚重写的！
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(content, list);
                    lv_list.setAdapter(re_ad);
                }
                if (position == 3) {
                    data.clear();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).get("scope").equals("驳回")) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd_tv", "资产编号");
                            map.put("creator_tv", "存放位置");
                            map.put("sum_tv", "归还部门");
                            map.put("state_tv", "归还人");
                            map.put("scope_tv", "状态");
                            map.put("Date_created_tv", "申请时间");
                            map.put("Inventory_date_tv", "归还时间");
                            map.put("scope", list.get(i).get("scope"));
                            map.put("state", list.get(i).get("state"));
                            map.put("odd", list.get(i).get("odd"));
                            map.put("Date_created", list.get(i).get("Date_created"));
                            map.put("creator", list.get(i).get("creator"));
                            map.put("sum", list.get(i).get("sum"));
                            map.put("Inventory_date", list.get(i).get("Inventory_date"));
                            data.add(map);
                        }
                    }
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(content, data);
                    lv_list.setAdapter(re_ad);
                }
                if (position == 2) {
                    data.clear();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).get("scope").equals("通过")) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd_tv", "资产编号");
                            map.put("creator_tv", "存放位置");
                            map.put("sum_tv", "归还部门");
                            map.put("state_tv", "归还人");
                            map.put("scope_tv", "状态");
                            map.put("Date_created_tv", "申请时间");
                            map.put("Inventory_date_tv", "归还时间");
                            map.put("scope", list.get(i).get("scope"));
                            map.put("state", list.get(i).get("state"));
                            map.put("odd", list.get(i).get("odd"));
                            map.put("Date_created", list.get(i).get("Date_created"));
                            map.put("creator", list.get(i).get("creator"));
                            map.put("sum", list.get(i).get("sum"));
                            map.put("Inventory_date", list.get(i).get("Inventory_date"));
                            data.add(map);
                        }
                    }
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(content, data);
                    lv_list.setAdapter(re_ad);
                }
                if (position == 1) {
                    data.clear();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).get("scope").equals("申请中")) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd_tv", "资产编号");
                            map.put("creator_tv", "存放位置");
                            map.put("sum_tv", "归还部门");
                            map.put("state_tv", "归还人");
                            map.put("scope_tv", "状态");
                            map.put("Date_created_tv", "申请时间");
                            map.put("Inventory_date_tv", "归还时间");
                            map.put("scope", list.get(i).get("scope"));
                            map.put("state", list.get(i).get("state"));
                            map.put("odd", list.get(i).get("odd"));
                            map.put("Date_created", list.get(i).get("Date_created"));
                            map.put("creator", list.get(i).get("creator"));
                            map.put("sum", list.get(i).get("sum"));
                            map.put("Inventory_date", list.get(i).get("Inventory_date"));
                            data.add(map);
                        }
                    }
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(content, data);
                    lv_list.setAdapter(re_ad);
                }
            }
        }).show());

    }

    @Override
    public void onStart() {
        Timer timer = new Timer();//实例化 Timer类
        timer.schedule(new TimerTask() {
            public void run() {
                load();
                this.cancel();
            }
        }, 300);//五百毫秒
        super.onStart();
    }

    private void load() {
//        new Thread() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient client =new OkHttpClient
//                .Builder()
//                .hostnameVerifier(new AllowAllHostnameVerifier())
//                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                .readTimeout(500, TimeUnit.SECONDS)
//                .build();
//                    RequestBody requestBody = new FormBody.Builder()
//                            .add("userId", Since_case.getInstance().getUserId())
//                            .build();
//                    Request request = new Request.Builder()
//                            .url(url)
//                            .post(requestBody).build();
//                    Response response = client.newCall(request).execute();
//                    String responseData = response.body().string();
//                    Log.d(TAG, "responseData: " + responseData);
//                    showResponse(responseData);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();
        List<ReceivesDetailNew> receivesDetailNewList = new ArrayList<>();


        User user = MyDataBase.init(content).userDao().getUserById(Since_case.getInstance().getUserId());
        if (user != null) {
            List<Returns> returnsList = MyDataBase.init(content).returnsDao().getAllData();
            for (Returns returns : returnsList) {
                ReceivesDetailNew receivesDetailNew = new ReceivesDetailNew();
                receivesDetailNew.setDate(returns.getDate());
                receivesDetailNew.setAssetNumber(returns.getAssetNumber());
                receivesDetailNew.setRedate(returns.getRdate());
                receivesDetailNew.setDeptId(returns.getDeptId());
                receivesDetailNew.setPlace(MyDataBase.init(content).placeDao().getNameById(returns.getPlace()));
                receivesDetailNew.setUserId(MyDataBase.init(content).userDao().getNameByIds(returns.getUserId()));
                receivesDetailNew.setStatus(returns.getStatus());

                receivesDetailNewList.add(receivesDetailNew);
            }
        }



//        List<ReceivesDetail> receivesDetailList = MyDataBase.init(content).receivesDetailDao().getAllReceivesDetail();
//
//        for (int position = 0; position < receivesDetailList.size(); position++) {
//            String deptId = MyDataBase.init(content).assetDao().getNumberByIds(receivesDetailList.get(position).getAssetId()).getDeptId();
//            String place = MyDataBase.init(content).assetDao().getNumberByIds(receivesDetailList.get(position).getAssetId()).getPlace();
//            String status = MyDataBase.init(content).assetDao().getNumberByIds(receivesDetailList.get(position).getAssetId()).getStatus();
//
//            ReceivesDetailNew receivesDetailNew = new ReceivesDetailNew();
//            receivesDetailNew.setDate("");
//            receivesDetailNew.setAssetNumber(receivesDetailList.get(position).getAssetId());
//            receivesDetailNew.setRedate("");
//            receivesDetailNew.setDeptId(MyDataBase.init(content).deptDao().getNameById(deptId));
//            receivesDetailNew.setPlace(MyDataBase.init(content).placeDao().getNameById(place));
//            receivesDetailNew.setUserId(MyDataBase.init(content).userDao().getNameByIds(Since_case.getInstance().getUserId()));
//            receivesDetailNew.setStatus(status);
//
//            receivesDetailNewList.add(receivesDetailNew);
//        }

        Gson gson = new Gson();
        String responseData = gson.toJson(receivesDetailNewList);
        Log.d(TAG, "responseData: " + responseData);
        showResponse(responseData);

    }

    private void showResponse(final String responseData) {
        LogUtils.d(responseData);
        if (responseData.equals("[]")) {
            content.showToast("无归还记录");
        }
        list.clear();
        mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
        Gson gson = new Gson();
        List<Repairs_bean> userList = gson.fromJson(responseData, new TypeToken<List<Repairs_bean>>() {
        }.getType());
        Log.d(TAG, "userList: " + new Gson().toJson(userList));
        for (int i = userList.size() - 1; i >= 0; i--) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("odd_tv", "资产编号");
            map.put("creator_tv", "归还位置");//     map.put("creator_tv", "存放地点");
            map.put("sum_tv", "物资名称");//   map.put("sum_tv", "归还部门");
            map.put("state_tv", "归还人");
            map.put("scope_tv", "状态");
            map.put("Date_created_tv", "申请时间");
            map.put("Inventory_date_tv", "归还时间");
            map.put("odd", userList.get(i).getAssetNumber());
            if (TextUtils.isEmpty(userList.get(i).getRedate())) {
                map.put("Inventory_date", "");
            } else {
                map.put("Inventory_date", userList.get(i).getRedate().substring(0, 10));
            }
            map.put("creator", userList.get(i).getPlace());
            map.put("sum", MyDataBase.init(content).assetDao().queryAllByNumber(userList.get(i).getAssetNumber()).getAssetName());
            if (TextUtils.isEmpty(userList.get(i).getDate())) {
                map.put("Date_created", "");
            } else {
                map.put("Date_created", userList.get(i).getDate().substring(0, 10));
            }
            String zt = "";
            if (userList.get(i).getStatus().equals("0")) {
                zt = "申请中";
            }
            if (userList.get(i).getStatus().equals("1")) {
                zt = "通过";
            }
            if (userList.get(i).getStatus().equals("2")) {
                zt = "驳回";
            }
            if (userList.get(i).getStatus().equals("4")) {
                zt = "归还";
            }
            map.put("scope", zt);
            map.put("state", userList.get(i).getUserId());
            list.add(map);
        }
        content.runOnUiThread(() -> {
            Public_list_item_Adapter re_ad = new Public_list_item_Adapter(content, list);
            lv_list.setAdapter(re_ad);
        });
    }

}
